<template>
  <div class="message">
    <el-popover placement="bottom" :width="310" trigger="click">
      <template #reference>
        <el-badge :value="unreadMessagesCount" class="item">
          <i :class="'iconfont icon-xiaoxi'" class="toolBar-icon"></i>
        </el-badge>
      </template>
      <el-dialog
      title="提示"
      v-model="centerDialogVisible"
      width="40%"
      center>
      <el-form :model="currentMessage" class="custom-form">
<!--        <el-form-item label="ID">-->
<!--          <span>{{ currentMessage.id }}</span>-->
<!--        </el-form-item>-->
        <el-form-item label="轨道区段：">
          <span>{{ currentMessage.trackSectionName }}</span>
        </el-form-item>
        <el-form-item label="开始时间：">
          <span>{{ currentMessage.startTime }}</span>
        </el-form-item>
        <el-form-item label="结束时间：">
          <span>{{ currentMessage.endTime }}</span>
        </el-form-item>
        <el-form-item label="故障概率：">
          <span>{{ currentMessage.faultProbability }}</span>
        </el-form-item>
        <el-form-item label="故障名称：">
          <span>{{ currentMessage.faultName }}</span>
        </el-form-item>
        <el-form-item label="故障区域：">
          <span>{{ currentMessage.faultArea }}</span>
        </el-form-item>
        <el-form-item label="故障设备：">
          <span>{{ currentMessage.falutFacility }}</span>
        </el-form-item>
        <el-form-item label="故障等级：">
          <span>{{ currentMessage.faultDangerLevel }}</span>
        </el-form-item>
        <el-form-item label="故障现象：">
          <span>{{ currentMessage.faultPhenomenon }}</span>
        </el-form-item>
        <el-form-item label="维修建议：">
          <span>{{ currentMessage.repairAdvice }}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="navigateToRealTimeDiagnosis">历史告警记录</el-button>
      </span>
    </el-dialog>
      <el-tabs v-model="activeName">
        <el-tab-pane :label="'通知(' + unreadMessagesCount + ')'" name="first">
          <div class="message-list">
            <div v-for="(item, index) in displayedItems" :key="index" class="message-item">
<!--              <img src="@/assets/images/msg01.png" alt="" class="message-icon" />-->

              <div class="message-content" @click="openItem(item.id)">
                <span class="message-title">{{ item.title }}</span>
                <span class="message-date">{{ item.area }}</span>
              </div>
              <img
                v-if="String(item.read).toLowerCase() !== 'true'"
                style="width: 15px; height: 15px;"
                src="@/assets/images/redpoint.png"
                alt=""
                class="message-icon"
              />
            </div>
            <el-button type="primary" @click="toggleShowAll">{{ showAll ? '显示部分' : '显示全部' }}</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="消息(0)" name="second">
          <div class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无消息</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="代办(0)" name="third">
          <div class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无代办</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import * as mqtt from "mqtt/dist/mqtt.min";
import { useRouter } from 'vue-router'; // 引入 useRouter
import { queryalarmNotificationDetail, queryAlarmNotification, updatealarmNotificationDetail } from "@/api/modules/new2";

const router = useRouter(); // 使用 useRouter

const activeName = ref("first");
const centerDialogVisible = ref(false);
const messageItems = ref([]);
const currentMessage = ref("");

const showAll = ref(false);
const displayedItems = computed(() => {
  return showAll.value ? messageItems.value : messageItems.value.slice(-4);
});

const unreadMessagesCount = computed(() => {
  return messageItems.value.filter(item => String(item.read).toLowerCase() !== 'true').length;
});



const toggleShowAll = () => {
      showAll.value = !showAll.value;
    };
// const openItem = (index) => {
//   currentMessage.value = messageItems.value[index].content;
//   centerDialogVisible.value = true;
// };
const openItem = async (id) => {
  try {
    // console.log("id", id);

    // 根据 id 查找消息项
    const selectedItem = messageItems.value.find(item => item.id === id);

    if (selectedItem) {
      const selectedItemId = selectedItem.alarmId;


      const params = {
        pageNum: 1,
        pageSize: 3,
        alarmId: selectedItemId,
        id: id,
      };

      const response = await queryalarmNotificationDetail(params);

      if (response && response.data) {
        currentMessage.value = response.data.list[0];

        centerDialogVisible.value = true;

        // 更新消息项的 read 状态
        selectedItem.read = true;


        // 部分显示红点问题
        if (!showAll.value) {
          // 刷新 displayedItems
          displayedItems.value = [...messageItems.value.slice(-4)];
        }

        // 调用 updatealarmNotificationDetail 接口
        await updatealarmNotificationDetail({ id: id });
      }
    } else {
      console.error('Message item not found');
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};


const fetchInitialMessages = async () => {
  try {
    // 调用接口获取初始数据
    const params = {
      pageNum: 1,
      pageSize: 1000,
    };
    const response = await queryAlarmNotification(params);

    // 假设返回的数据结构为 response.data，其中包含我们需要的信息
    if (response && response.data) {
      // 将数据保存到 messageItems 数组中
      messageItems.value = response.data.list.map(item => ({
        title: item.faultName,
        area: `${item.trackSectionName} at ${item.startTime}`,
        content: `${item.faultName} detected in section ${item.trackSectionName} at ${item.startTime}`,
        alarmId: item.alarmId,
        read: String(item.isRead).toLowerCase(),
        id: item.id,
      }));
      // // 数据量翻三倍
      // messageItems.value = messageItems.value.concat(messageItems.value, messageItems.value);

      console.log(messageItems.value)
    }



  } catch (error) {
    console.error('Error fetching initial messages:', error);
  }
};
// dao
const navigateToRealTimeDiagnosis = () => {
  centerDialogVisible.value = false;
  router.push('/diagnosisCenter/realTimeDiagnosis'); // 导航到指定页面
};

onMounted(async () => {
  await fetchInitialMessages();

  const client = mqtt.connect('ws://59.110.225.60:8083/mqtt'); // 使用ws协议
  // console.log('Connected ?');
  client.on('connect', () => {
    console.log('Connected to MQTT broker');
    client.subscribe('real_time_alarm_message');
  });

  client.on('message', (topic, message) => {
    const parsedMessage = JSON.parse(message.toString());
    console.log("parsedMessage : ", parsedMessage);

    // 检查属性是否存在，并提供默认值
    const faultName = parsedMessage.data.faultName || 'Unknown fault';
    console.log(faultName)
    const trackSectionName = parsedMessage.data.trackSectionName || 'Unknown section';
    const startTime = parsedMessage.data.startTime || 'Unknown time';
    const alarmId = parsedMessage.data.alarmId || 'Unknown time';

    messageItems.value.push({
      title: faultName,
      area: `${trackSectionName} at ${startTime}`,
      content: `${faultName} detected in section ${trackSectionName} at ${startTime}`,
      alarmId: alarmId
    });
  });

  client.on('error', (error) => {
    console.error('MQTT error:', error);
  });
});
</script>

<style scoped lang="scss">
.custom-form {
  .el-form-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    padding: 0 0;
    background-color: #fafafa;
    &:nth-child(odd) {
      background-color: #56faba;
    }
    .el-form-item__label {
      font-weight: bold;
      font-size: 14px;
      color: #606266;
    }
    .el-form-item__content {
      font-size: 14px;
      color: #303133;
    }
    .highlight {
      color: #409eff; // 特别高亮的内容
      font-weight: bold;
    }
  }
}

.message-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  line-height: 45px;
}
.message-list {
  display: flex;
  flex-direction: column;
  height: 300px; /* 设置固定高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
  .message-item {
    display: flex;
    align-items: center;
    padding: 20px 0;
    border-bottom: 1px solid var(--el-border-color-light);
    &:last-child {
      border: none;
    }
    .message-icon {
      width: 40px;
      height: 40px;
      margin: 0 20px 0 5px;
    }
    .message-content {
      display: flex;
      flex-direction: column;
      .message-title {
        margin-bottom: 5px;
      }
      .message-date {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}
</style>
